package aut;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AutoCompleteServlet extends HttpServlet {
    private ServletContext context;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.context = config.getServletContext();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        String targetId = request.getParameter("id");
        String attribute = request.getParameter("attribute");
        StringBuffer stringBuffer = new StringBuffer();

        if(targetId!=null) {
            targetId = targetId.trim().toLowerCase();
        } else {
            context.getRequestDispatcher("/error.jsp").forward(request, response);
        }
        try {
            stringBuffer = new AutoList().getList(attribute, targetId);
        } catch (WrongAttributeException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not found attribute - "+attribute);
        }
        if (stringBuffer.length()!=0) {
            response.setContentType("text/xml");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write("<objects>" + stringBuffer.toString() + "</objects>");
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }
}
